package com.fingard.text;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

/**
 * Created by Lewis on 2017/12/6.
 */
public class AESHelper {
    /**
     * AES加密
     * 		-- 生成加密数据
     */
    public static String encodeAES(byte[] key, byte[] content) throws Exception {
        // 不是16的倍数的，补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }

        SecretKey secretKey = new SecretKeySpec(key, "AES");
        IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] tgtBytes = cipher.doFinal(content);
        return new BASE64Encoder().encode(tgtBytes);
    }

    /**
     * AES解密
     * 		-- 返回解密后原文
     */
    public static byte[] decodeAES(byte[] key, byte[] content) throws Exception {
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }

        SecretKey secretKey = new SecretKeySpec(key, "AES");
        IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] tgtBytes = cipher.doFinal(content);
        return tgtBytes;
    }

    //测试代码
    public static void main(String args[]) throws Exception{
        String endata = encodeAES("12345678".getBytes(),"你好".getBytes());
        String cipher = "8S0arnb3E4iL2B48nVqlIBNGfvCLuxwumuNizh3IvA0gbfOOVqvZymoI1UTpmQSmWTb/4Cp9mJno\n" +
                "ziecekStOk/y+5JHOd1u8nco3Mb3FQY=#20171205";
        System.out.println(endata);
        System.out.println(new String(decodeAES(cipher.split("#")[1].getBytes(),new BASE64Decoder().decodeBuffer(cipher.split("#")[0]))));

    }
}
